package fun.linze.wallpaperwebsite.filter;

import fun.linze.wallpaperwebsite.util.JwtUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

public class JwtAuthenticationFilter implements Filter {
    private String[] excludeUrls = new String[]{};

    @Override
    public void init(jakarta.servlet.FilterConfig filterConfig) throws jakarta.servlet.ServletException {
        String exclude = filterConfig.getInitParameter("excludeUrls");
        if (exclude != null && !exclude.isEmpty()) {
            excludeUrls = exclude.split(",");
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String path = httpRequest.getRequestURI();
        for (String url : excludeUrls) {
            if (url != null && !url.isEmpty() && path.matches(url.trim())) {
                chain.doFilter(request, response);
                return;
            }
        }
        String authHeader = httpRequest.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            if (JwtUtil.validateToken(token)) {
                chain.doFilter(request, response);
                return;
            }
        }
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.getWriter().write("Unauthorized");
    }
}